package com.simple.crawler.aop;

import com.simple.crawler.utils.CrawlerLogger;
import com.simple.crawler.utils.ReflectUtils;
import com.simple.crawler.utils.StringUtils;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public interface Listener extends MethodInterceptor {

    CrawlerLogger logger = CrawlerLogger.getLogger(Listener.class);

    default boolean filter(String method) {
        return false;
    }

    default void before(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Exception {

    }

    default void after(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Exception {

    }

    default Object invoke(Object o, Method method, Object[] objects, MethodProxy proxy) throws Throwable {
        String tag = StringUtils.getId(16);
        long start = System.currentTimeMillis();
        logger.debug("[{}][执行类:{}，执行方法:{}，方法参数:{}]", tag, o.getClass().toString(), method.getName(), StringUtils.toArrJson(objects));
        before(o, method, objects, proxy);
        Object result = proxy.invokeSuper(o, objects);
        after(o, method, objects, proxy);
        long end = System.currentTimeMillis();
        logger.debug("[{}][本次共耗时:{}ms]",  tag, end - start);
        return result;
    }

    @Override
    default Object intercept(Object o, Method method, Object[] objects, MethodProxy proxy) throws Throwable {
        if (!filter(method.getName())) {
            return proxy.invokeSuper(o, objects);
        }
        return invoke(o, method, objects, proxy);
    }
}
